
/**   
*    
* 项目名称：a_yongan   
* 类名称：OutsourcingInServiceImpl   
* 类描述：   
* 创建人：liubo   
* 创建时间：2018年6月30日 上午10:59:50    
* 修改时间：2018年6月30日 上午10:59:50   
* 修改备注：   
* @version    
*    
*/
package com.yongan.purchase.service.impl;

import java.util.ArrayList;
import java.util.List;
import java.util.UUID;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.DigestUtils;

import com.yongan.purchase.dao.PurchaseGoodsDetailsDao;
import com.yongan.purchase.dao.PurchaseReturnDao;
import com.yongan.purchase.entity.PurchaseGoodsDetails;
import com.yongan.purchase.entity.PurchaseReturn;
import com.yongan.purchase.service.PurchaseReturnService;
import com.yongan.user.enums.UserStatEnum;
import com.yongan.user.exception.UserException;
import com.yongan.util.Execution;
import com.yongan.warehouse.dao.GoodsinformationDao;

/**
 * @author liubo
 *
 */
@Service
public class PurchaseReturnServiceImpl implements PurchaseReturnService{

	private Logger logger = LoggerFactory.getLogger(this.getClass());
	@Autowired
	private PurchaseReturnDao purchaseReturnDao;
	@Autowired
	private PurchaseGoodsDetailsDao detailsDao;
	@Autowired
	private GoodsinformationDao goodsinformationDao;
	private final String slat = "dsjdajsdkHJJHAJAKdsd921e0p12*DAe#@$@!qew";
	@Override
	public List<PurchaseReturn> getPurchaseReturnList(int offset, int limit) {
		return purchaseReturnDao.queryAll(offset, limit);
	}

	
	@Override
	public PurchaseReturn getPurchaseReturnById(String purchaseReturnId) {
		// TODO 自动生成的方法存根
		PurchaseReturn purchaseReturn = purchaseReturnDao.queryById(purchaseReturnId);
		purchaseReturn.setDetails(detailsDao.queryAllByTopId(purchaseReturnId));
		return purchaseReturn;
	}

	

	@Override
	@Transactional
	public Execution executePurchaseReturn(PurchaseReturn purchaseReturn,
			String purchaseReturnId, String md5) throws UserException {
		if(md5 == null || !md5.equals(getMD5(purchaseReturnId))){
			//throw new UserException("user data rewrite");
		}
		//System.out.println("otherGoodOutId:"+otherGoodOutId);
		//System.out.println(otherGoodOut.toString());
		List<PurchaseGoodsDetails> details =null;
		try{
			if(purchaseReturn == null){
				//PurchaseReturn readDell = purchaseReturnDao.queryById(purchaseReturnId);
				details = detailsDao.queryAllByTopId(purchaseReturnId);
				if(!(details==null)){
					for(PurchaseGoodsDetails goodDetails:details){
						reduceNumber(goodDetails, "add");
					}
				}
				int deleteCount = purchaseReturnDao.deletePurchaseReturn(purchaseReturnId);
				int deleteInGoodDetailsCount = detailsDao.deleteAllPurchaseGoodsDetails(purchaseReturnId);
				if(deleteCount<=0 & deleteInGoodDetailsCount<=0){
					throw new UserException("delete failed");
				}else{
					return new Execution(purchaseReturnId, UserStatEnum.SUCCESS);
				}
			}else if((purchaseReturnId.equals(""))){
				details = purchaseReturn.getDetails();
				int goodDetailsaddcount = 1;
				if(!(details==null)){
					for(PurchaseGoodsDetails goodDetails:details){
						goodDetails.setpurchasegoodsdetailsId(UUID.randomUUID().toString());;
						goodDetails.setTopId(purchaseReturn.getPurchaseReturnId());;
						int addInGoodDetailsCount = detailsDao.insertPurchaseGoodsDetails(goodDetails);
						if(addInGoodDetailsCount<=0){
							goodDetailsaddcount = addInGoodDetailsCount;
						}
						reduceNumber(goodDetails, "reduce");
					}
				}
				int addCount = purchaseReturnDao.insertPurchaseReturn(purchaseReturn);
				if(addCount<=0 & goodDetailsaddcount<=0){
					throw new UserException("add failed");
				}else{
					return new Execution(purchaseReturn.getPurchaseReturnId(), UserStatEnum.SUCCESS);
				}
			}else if(!(purchaseReturnId.equals(""))){
				List<PurchaseGoodsDetails> oldList = detailsDao.queryAllByTopId(purchaseReturnId);
				List<String> newList = new ArrayList<String>();
				//String[] newList;
				details = purchaseReturn.getDetails();
				int goodDetailscount = 1;
				if(!(details==null)){
					for(PurchaseGoodsDetails goodDetails:details){
						//减去新保存的列表
						reduceNumber(goodDetails, "reduce");
						//如果更新的总单据下面的子单据ID为空，则为新增，否则是修改
						if(goodDetails.getpurchasegoodsdetailsId().equals("")){
							goodDetails.setpurchasegoodsdetailsId(UUID.randomUUID().toString());
							goodDetails.setTopId(purchaseReturn.getPurchaseReturnId());
							int ua = detailsDao.insertPurchaseGoodsDetails(goodDetails);
							if(ua<=0){
								goodDetailscount = ua;
							}
						}else{
							//reduceNumber(goodDetails, "reduce");
							int uu = detailsDao.updatePurchaseGoodsDetails(goodDetails);
							if(uu<=0){
								goodDetailscount = uu;
							}else{
								newList.add(goodDetails.getpurchasegoodsdetailsId());
							}
						}
					}
				}
				if (oldList != null) {
					for (PurchaseGoodsDetails old : oldList) {
						// 减去旧列表在库存中的数量
						reduceNumber(old, "add");
						Boolean sf = false;
						if (newList != null) {
							for (String newl : newList) {
								if (old.getpurchasegoodsdetailsId().equals(newl)) {
									sf = true;
								}
							}
							if (!sf) {
								detailsDao.deletePurchaseGoodsDetails(old.getpurchasegoodsdetailsId());
							}
						}
					}
				}

				int updateCount = purchaseReturnDao.updatePurchaseReturn(purchaseReturn);
				if(updateCount<=0 & goodDetailscount<=0){
					throw new UserException("update failed");
				}else{
					return new Execution(purchaseReturnId, UserStatEnum.SUCCESS);
				}
			}else{
				throw new UserException("parameter error");
			}
			
		}catch(Exception e){
			logger.error(e.getMessage(),e);
			throw new UserException("inner error:"+e.getMessage());
		}
	}

	
	@Override
	public int getCount() {
		// TODO 自动生成的方法存根
		return purchaseReturnDao.queryCount();
	}
	
	private String getMD5(String Id){
		String base = Id + "/" + slat;
		String md5 = DigestUtils.md5DigestAsHex(base.getBytes());
		return md5;
	}
	
	public PurchaseReturnServiceImpl() {
		super();
		// TODO 自动生成的构造函数存根
	}


	public int reduceNumber(PurchaseGoodsDetails igd,  String type){
		return goodsinformationDao.reduceNumber(igd.getpurchasegoodsdetailsHpbm()
				, type, Integer.parseInt(igd.getpurchasegoodsdetailsHpsl())
				, Integer.parseInt(igd.getpurchasegoodsdetailsHpsl()));
	}
	
}
